
export default {
    namespaced:true,
    state:{
        carts:[]
    },
    mutations:{
        //加入到购物车的方法
        SET_CART(state,payload){
            let target = state.carts.find(item=>item.id===payload.id)
            if(target){//carts 里面有这条数据，让数量+1
                target.count ++
            }else{//没有，就声明一条数据
                let obj = {
                    id:payload.id,
                    title:payload.title,
                    price:payload.price,
                    count:1
                }
                state.carts.push(obj)
            }
        },
        //减少购物车的数量
        DEL_INVENTORY(state,payload){
            let target = state.carts.find(item=>item.id===payload.id)
            target.count --
            if(target.count===0){
                state.carts = state.carts.filter(item=>item.id!==payload.id)
            }
        }
    },
    actions:{
        //不同模块之间操作mutataion和action
        ADD_CART(context,payload){
            // console.log(context)
            // console.log(payload)
            context.commit('SET_CART',payload)
            //触发其他模块的mutations
            context.commit('product/DEL_INVENTORY',payload,{root:true})
        },
        //减少购物车数量
        DEL_CART(context,payload){
            context.commit('DEL_INVENTORY',payload)
            context.commit('product/ADD_INVENTORY',payload,{root:true})
        }
        
    },
    getters:{
        MONEY(state){
           return (state.carts.reduce((total,item)=>{
              return total += item.price*item.count
            },0)).toFixed(2)
        }
    }
}